package com.csii.adhoc.controller.common;

import com.csii.adhoc.info.user.UserPo;
import com.csii.adhoc.info.user.service.UserService;
import com.csii.adhoc.util.encrypt.DESUtil;
import com.csii.adhoc.util.encrypt.ShiroKit;
import com.csii.result.APIResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @description: 公共接口控制层
 * @author: panChuanJiang
 * @create: 2021-02-18 09:03
 */
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {
    @Resource
    private UserService userService;

    @RequestMapping("login")
    public APIResult<?> login(@RequestBody UserPo userPo) {
        //用户号
        String username = userPo.getUsername();
        //密码
        String password = userPo.getPassword();
        UserPo user = userService.selectUserByUserName(username);
        if (null == user) {
            log.info("用户不存在");
            return APIResult.failResult(username, "用户不存在");
        }
        String security;
        try {
            security = ShiroKit.md5(DESUtil.decryption(password, "38442065" + username), user.getSalt());
        } catch (Exception e) {
            log.error("错误信息：{}", e.getMessage());
            return APIResult.failResult(e, "密码解析失败");
        }
        if (!security.equals(user.getPassword())) {
            return APIResult.failResult(username, "密码错误,请重新输入!");
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
        } catch (Exception e) {
            log.error("错误信息：{}", e.getMessage());
            return APIResult.failResult(e, "shiro登陆异常");
        }
        return APIResult.successResult(user);
    }

    /**
     * 查询当前用户信息
     *
     * @return 当前用户信息
     */
    @RequestMapping("queryUserInfo")
    public APIResult<?> queryUserInfo() {
        String userName = String.valueOf(SecurityUtils.getSubject().getPrincipal());
        if (StringUtils.isEmpty(userName)) {
            return APIResult.failResult(userName, "获取不到当前登陆用户");
        }
        UserPo userPo = userService.selectUserByUserName(userName);
        if (userPo != null) {
            userPo.setSalt(null).setPassword(null);
        }
        return APIResult.successResult(userPo);
    }

    /**
     * 登出
     */
    @RequestMapping("logout")
    public APIResult<String> logout() {
        SecurityUtils.getSubject().logout();
        return APIResult.successResult("登出成功");
    }
}
